package com.cuiweiyou.phpjavaencrypt;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;

/**
 * <b>类名</b>: DESUtil，DES方式加密解密工具 <br/> 
 * <b>说明</b>: TODO 兼容PHP <br/>
 * <b>创建</b>: 2016年1月5日 15:02:17 <br/> 
 * 
 * @author TS-YFZX-CWY , weiyou.cui@ts-tech.com.cn <br/> 
 * @version  1 <br/>
 */
public class DESUtil {
	
	/** des key */
	private static String DES_KEY = "12345678";

	/** 密文转换器 */
	private static Cipher cipher;
	/** 安全相关随机码  */
	private static SecureRandom sr;
	/** 密钥 */ 
	private static SecretKey securekey;
	
	private DESUtil() {
	}

	/**
	 * 加密
	 * 
	 * @param datas 目标明文
	 * @return 密文
	 */
	public static String encrypt(String datas) {
		try {
			if(null == cipher)
				getCipher();
			
			cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);                // 用密钥初始化Cipher对象为加密模式

			byte[] bt = cipher.doFinal(datas.getBytes("utf-8"));            // 执行加密
			String strs = new BASE64Encoder().encode(bt);

			return strs;

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 解密
	 * 
	 * @param datas 目标密文
	 * @return  明文
	 */
	public static String decrypt(String datas) {
		try {
			if(null == cipher)
				getCipher();
			
			cipher.init(Cipher.DECRYPT_MODE, securekey, sr);      // 解密模式

			byte[] buf = new BASE64Decoder().decodeBuffer(datas);
			byte[] bt = cipher.doFinal(buf);

			return new String(bt);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
	
	/**
	 * <b>功能</b>：getCipher，获取密文转换器<br/> 
	 * <b>创建</b>：2016-1-5下午3:21:36<br/>
	 * @return cipher <br/> 
	 * 
	 * @author TS-YFZX-CWY, weiyou.cui@ts-tech.com.cn
	 */
	private static void getCipher() throws Exception {
		sr = new SecureRandom();                                                   // 安全随机码
		DESKeySpec dks = new DESKeySpec(DES_KEY.getBytes("utf-8"));                // 创建DES密钥模具
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");         // 获取密钥工厂
		securekey = keyFactory.generateSecret(dks);                                // 根据模具生成密钥
		
		cipher = Cipher.getInstance("DES");                                        // 得到指定算法的密文转换器
	}
}
